import { HttpConfigType } from "types";
import { urlStringfy } from "utils";
import * as auth from "auth-provider";
import { useAuth } from "context/auth-context";
import { useCallback } from "react";

const apiUrl = process.env.REACT_APP_API_URL;

export const server = async (
  endpoint: string,
  { data, token, headers, ...others }: HttpConfigType = {}
) => {
  const config = {
    method: "GET",
    headers: {
      Authorization: token ? `Bearer ${token}` : "",
      ...(data ? { "Content-Type": "application/json" } : {}),
    },
    ...others,
  };

  if (config.method.toUpperCase() === "GET") {
    endpoint += urlStringfy(data, true);
  } else {
    config.body = JSON.stringify(data);
  }

  return fetch(`${apiUrl}/${endpoint}`, config).then(async (res) => {
    if (res.status === 401) {
      await auth.logout();
      window.location.reload();
      return Promise.reject({ message: "请重新登录" });
    }

    const result = await res.json();
    return res.ok ? result : Promise.reject(result);
  });
};

export const useServer = () => {
  const { user } = useAuth();

  return useCallback(
    (...[endpoint, config]: Parameters<typeof server>) => {
      return server(endpoint, { ...config, token: user?.token });
    },
    [user?.token]
  );
};

export default useServer;

export * from "./useProjects";
export * from "./useUser";
export * from "./userAddProject";
export * from "./userEditProject";
export * from "./useProject";
export * from "./useKanbans";
export * from "./useTasks";
export * from "./useTask";
export * from "./useTaskTypes";
export * from "./useAddKanban";
export * from "./useAddTask";
export * from "./useEditTask";
export * from "./useDeleteTask";
export * from "./useDeleteKanban";
export * from "./useReorderKanban";
export * from "./useReorderTask";
export * from "./useAddEpic";
export * from "./useDeleteEpic";
export * from "./useEpics";
